// store/index.js
import user from './user'
import cart from './cart'

// 合并所有模块
const modules = {
  user,
  cart
}

// 状态管理类
class Store {
  constructor(modules) {
    this.modules = modules
    this.state = {}
    this.mutations = {}
    this.actions = {}
    
    // 初始化模块
    this.initModules(modules)
  }
  
  // 初始化模块
  initModules(modules) {
    Object.keys(modules).forEach(key => {
      const module = modules[key]
      this.initModule(key, module)
    })
  }
  
  // 初始化单个模块
  initModule(key, module) {
    // 初始化状态
    this.state[key] = { ...module.state }
    
    // 初始化mutations
    if (module.mutations) {
      Object.keys(module.mutations).forEach(mutationKey => {
        this.mutations[`${key}/${mutationKey}`] = (...args) => {
          module.mutations[mutationKey].apply(this, [this.state[key], ...args])
        }
      })
    }
    
    // 初始化actions
    if (module.actions) {
      Object.keys(module.actions).forEach(actionKey => {
        this.actions[`${key}/${actionKey}`] = (...args) => {
          return module.actions[actionKey].apply(this, [this, ...args])
        }
      })
    }
  }
  
  // 提交mutation
  commit(type, payload) {
    if (this.mutations[type]) {
      this.mutations[type](payload)
    } else {
      console.error(`[vuex] unknown mutation type: ${type}`)
    }
  }
  
  // 分发action
  dispatch(type, payload) {
    if (this.actions[type]) {
      return this.actions[type](payload)
    } else {
      console.error(`[vuex] unknown action type: ${type}`)
      return Promise.reject(new Error(`unknown action type: ${type}`))
    }
  }
  
  // 获取状态
  getState() {
    return this.state
  }
}

// 创建store实例
const store = new Store(modules)

module.exports = store
